import os
import shutil
try:
    from .cvio import cvio
except:
    from cvio import cvio

def daiding_2_folder_mask(src):
    anns = cvio.load_ext_list(src, recursive=True, silent=False)
    n = len(anns)
    for i, ann in enumerate(anns, 1):
        print('[%d/%d]' % (i, n), os.path.basename(ann))
        ann_info = cvio.load_ann(ann)
        m = len(ann_info['shapes'])
        folder = ann.split(os.sep)[-2]
        for i in range(m):
            label = ann_info['shapes'][i]['label']
            if label == 'daiding_101':
                ann_info['shapes'][i]['label'] = folder
        ext = os.path.splitext(ann_info['imagePath'])[-1]
        imgsrc = os.path.splitext(ann)[0] + ext
        imgdst = os.path.join(src, os.path.basename(imgsrc))
        if os.path.exists(imgsrc) and not os.path.exists(imgdst):
            shutil.move(imgsrc, imgdst)
        anndst = os.path.basename(ann)
        if os.path.exists(anndst):
            ann_exists = cvio.load_ann(anndst)
            ann_info['shapes'] += ann_exists['shapes']
        cvio.write_ann(ann_info, os.path.join(src, anndst))

